//
//  ApplyConfirmationViewController.m
//  Jingjing
//
//  Created by user on 15/11/13.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ApplyConfirmationViewController.h"
#import "MyInfoViewController.h"
#import "SucessViewController.h"
#import "LoginViewController.h"
@interface ApplyConfirmationViewController()<UITextFieldDelegate>
@property (nonatomic,strong)UIScrollView * mainSrollView;
@property (nonatomic,strong)UIView       * examView;            //考试信息
@property (nonatomic,strong)UIView       * personalView;        //个人信息
@property (nonatomic,strong)UIButton     * storeBtn;             //确认按钮
@property (nonatomic,strong)UIView       * changeBtnView;       //修改信息view

@property (nonatomic,strong)UITextField *userNameTf;
@property (nonatomic,strong)UITextField *iphoneTf;
@property (nonatomic,strong)UITextField *emailTf;
@property (nonatomic,strong)UITextField *positionTf;

@end

@implementation ApplyConfirmationViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"报名"];
    [self.view addSubview:topView];
    
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    _mainSrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT- 64)];
    _mainSrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _mainSrollView.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    
    [self.view addSubview:_mainSrollView];
    
    [_mainSrollView addSubview:self.examView];//活动名称时间地点
   [_mainSrollView addSubview:self.personalView];//个人信息
    [_mainSrollView addSubview:self.storeBtn];
    _mainSrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _storeBtn.frame.size.height + _storeBtn.frame.origin.y + 16.0f);
    
    
}
- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark-----------------get方法创建控件
-(UIView *)examView
{
    CGFloat height1 = [UILabel height:_activityName widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:14]];
    
    CGFloat height2 = [UILabel height:_activityDestion widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:14]];
    if (!_examView)
    {
        _examView = [[UIView alloc]initWithFrame:CGRectMake(16.0f, 16.0f, SCREEN_WIDTH-32.0f, 68 + height1 + height2)];
        _examView.backgroundColor = [UIColor whiteColor];
        [_mainSrollView addSubview:_examView];

        
        NSArray * nameArr =@[@"活动名称",@"活动地点",@"时间"];
        NSArray * detailArr = @[_activityName,_activityDestion,_activityTime];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 16,70,  height1)];
        titleLabel.font = [UIFont systemFontOfSize:14.0f];
        titleLabel.text =  nameArr[0];
        titleLabel.textColor = kColorTEXT;
        [_examView addSubview:titleLabel];
        
        UILabel *titleTip = [[UILabel alloc]initWithFrame:CGRectMake(98, 16,SCREEN_WIDTH - 100-32, height1)];
        titleTip.text =  detailArr[0];
        titleTip.textColor = kColorTEXT;
        titleTip.font = [UIFont systemFontOfSize:14.0f];
        titleTip.numberOfLines = 0;
        [_examView addSubview:titleTip];
        
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(16,NH(titleTip)+10.0f, 70, height2)];
        label.text = nameArr[1];
        label.textColor = kColorTEXT;
        label.font = [UIFont systemFontOfSize:14];
        [_examView addSubview:label];
        
        UILabel * detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(98,NH(titleTip)+10.0f, SCREEN_WIDTH - 100-32, height2)];
        detailLabel.textColor = kColorTEXT;
        detailLabel.text = detailArr[1];
        detailLabel.numberOfLines = 0;
        detailLabel.font = [UIFont systemFontOfSize:14];
        [_examView addSubview:detailLabel];
        
        UILabel * destionTip = [[UILabel alloc]initWithFrame:CGRectMake(16,NH(detailLabel)+10.0f, 70, 30)];
        destionTip.text = nameArr[2];
        destionTip.textColor = kColorTEXT;
        destionTip.font = [UIFont systemFontOfSize:14];
        [_examView addSubview:destionTip];
        
        UILabel * destionLabel = [[UILabel alloc]initWithFrame:CGRectMake(98,NH(detailLabel)+10.0f, SCREEN_WIDTH - 100-32, 30)];
        destionLabel.textColor = kColorTEXT;
        destionLabel.text = detailArr[2];
        destionLabel.numberOfLines = 0;
        destionLabel.font = [UIFont systemFontOfSize:14];
        [_examView addSubview:destionLabel];
        
        
        
    }
    return _examView;
}
-(UIView *)personalView
{
    if (!_personalView)
    {
        //循环创建需要填入的label和textfield
        _personalView = [[UIView alloc]initWithFrame:CGRectMake(16.0f, _examView.frame.origin.y + _examView.frame.size.height + 20, SCREEN_WIDTH-32.0f, 208)];
        _personalView.backgroundColor = [UIColor whiteColor];
        
        NSArray * labelTextArr =@[@"姓名",@"电话",@"邮箱",@"职业"];
        
        for (int i = 0 ; i < 4; i++)
        {
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(16,16+i*52, 70, 20)];
            label.text = labelTextArr[i];
            label.font = [UIFont systemFontOfSize:14];
            [_personalView addSubview:label];
            
            
            
            UITextField *detailTF = [[UITextField alloc]initWithFrame:CGRectMake(98,16+i*52, SCREEN_WIDTH - 114-32, 20)];
            detailTF.tag = 10+i;
            detailTF.font = [UIFont systemFontOfSize:14];
            detailTF.textColor = [UIColor blackColor];
            detailTF.textAlignment = NSTextAlignmentRight;
            detailTF.delegate = self;
            [_personalView addSubview:detailTF];
            
            if (i==0) {
                if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"userName"]]) {
                    detailTF.placeholder = @"未填写";
                    detailTF.text = @"";
                    
                }else{
                    
                    detailTF.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
                    detailTF.text =  [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
                    detailTF.enabled = NO;
                  
                    
                }
                
                self.userNameTf = detailTF;

            }else if (i==1){
                if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]]) {
                    detailTF.placeholder = @"未填写";
                    detailTF.text = @"";
                }else{
                    detailTF.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"];
                    detailTF.text = detailTF.placeholder;
                    detailTF.enabled = NO;
                }
                self.iphoneTf = detailTF;
                
            }else if (i==2){
                if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"email"]]) {
                    detailTF.placeholder = @"未填写";
                    detailTF.text = @"";
                }else{
                    detailTF.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"email"];
                    detailTF.text = detailTF.placeholder;
                }
                self.emailTf = detailTF;
                
            }else{
                if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"position"]]) {
                    detailTF.placeholder = @"未填写";
                    detailTF.text = @"";
                }else{
                    detailTF.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"position"];
                    detailTF.text = detailTF.placeholder;
                }
                self.positionTf = detailTF;
                
            }
            
            
        }
        
    }
    
    
    
    return _personalView;
}
-(UIButton *)storeBtn
{
    if (!_storeBtn)
        
         _storeBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0-50, NH(_personalView)+16.0f, 100.0f, 44.0f)];
        [_storeBtn setTitle:@"确认报名" forState:UIControlStateNormal];
        [_storeBtn addTarget:self action:@selector(buttonApplyTheCourseTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_storeBtn setBackgroundColor:kColorOrangeNormal forState:UIControlStateNormal];
       [_storeBtn  setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
       [_storeBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
        _storeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        _storeBtn.layer.cornerRadius = 5;
        _storeBtn.layer.masksToBounds = YES;
        
  
    return _storeBtn;
}
#pragma mark-----------报名
-(void)buttonApplyTheCourseTapped:(id)sender
{
    
    if ([AccountTools isEmpty:self.emailTf.text]== NO&& [AccountTools validateEmail:self.emailTf.text]==NO) {
        ALERT_VIEW(@"邮箱输入不合法,请重新输入");
        return;
    }

    //    执行
    [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中"];
    [AppGlobalClass PostDataWithNSstring:UPDATEUSERINFO withDictionary:@{@"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"],@"userName":[[NSUserDefaults standardUserDefaults]objectForKey:@"userName"],@"mobile":[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"],@"address":[[NSUserDefaults standardUserDefaults]objectForKey:@"address"],@"email":self.emailTf.text,@"sex":[[NSUserDefaults standardUserDefaults]objectForKey:@"sex"],@"zipCode":[[NSUserDefaults standardUserDefaults]objectForKey:@"zipCode"],@"position":self.positionTf.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
          
            
            
            [AccountTools SaveUserToken:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] userName:[[NSUserDefaults standardUserDefaults]objectForKey:@"userName"] userCd:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"] address:[[NSUserDefaults standardUserDefaults]objectForKey:@"address"] email:self.emailTf.text zipCode:[[NSUserDefaults standardUserDefaults]objectForKey:@"zipCode"] position:self.positionTf.text sex:[[NSUserDefaults standardUserDefaults]objectForKey:@"sex"]];
            
            
               [self applyConfirmationRequest];

            
        }else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
        }
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } failure:^(NSError *error) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } networkerror:^(NSString *networkerror) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    }];


  
}
- (void)applyConfirmationRequest
{
    [[AnimationIndicator sharedIndicator]startAnimation];
    [AppGlobalClass PostDataWithNSstring:USERTAKEPARTACTIVITIES withDictionary:@{@"activitiesId":self.activityId,@"token":[AccountTools getUserToken]} success:^(NSDictionary *dictionary) {
        if ([[dictionary objectForKey:@"success"]isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            SucessViewController * vc = [[SucessViewController alloc]init];
            [self.navigationController pushViewController:vc animated:TRUE];
        }
        else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
        }
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:YES];
        
        
    } failure:^(NSError *error) {
        
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:YES];
        
    } networkerror:^(NSString *networkerror) {
        
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:YES];
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
   
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号在另一台机器登录，请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark------------alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //删除token等用户数据
    [AccountTools exitLogin];
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    loginViewCon.backBtHide = FALSE;
    [self presentViewController:loginViewCon animated:TRUE completion:^{
        //回到哪个界面
    }];
    
}
- (void)textFieldDidChangeCharcter:(id)sender
{
    
}


//键盘下降
- (void)keyboardHide:(NSNotification *)noti
{
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    _mainSrollView.contentOffset = CGPointMake(0, 0);
    [UIView commitAnimations];
}

//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    if (keyboardFrame.origin.y != SCREEN_HEIGHT) {
        CGFloat a = _mainSrollView.frame.size.height + _mainSrollView.frame.origin.y+80.0f;
        if (a < keyboardFrame.origin.y) {
            _mainSrollView.contentOffset = CGPointMake(0, 0);
        }else
        {
            _mainSrollView.contentOffset = CGPointMake(0, 200);
        }
        
    }
    
    [UIView commitAnimations];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}


@end
